package vip.xiaonuo.home.modular.setting.company.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.util.CommonAvatarUtil;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.dev.api.DevConfigApi;
import vip.xiaonuo.home.modular.setting.company.entity.HomeCompany;
import vip.xiaonuo.home.modular.setting.company.mapper.HomeCompanyMapper;
import vip.xiaonuo.home.modular.setting.company.param.HomeCompanyAddParam;
import vip.xiaonuo.home.modular.setting.company.param.HomeCompanyEditParam;
import vip.xiaonuo.home.modular.setting.company.param.HomeCompanyIdParam;
import vip.xiaonuo.home.modular.setting.company.param.HomeCompanyPageParam;
import vip.xiaonuo.home.modular.setting.company.service.HomeCompanyService;
import vip.xiaonuo.home.modular.structure.org.entity.HomeOrg;
import vip.xiaonuo.home.modular.structure.org.service.HomeOrgService;
import vip.xiaonuo.home.modular.structure.position.entity.HomePosition;
import vip.xiaonuo.home.modular.structure.position.service.HomePositionService;
import vip.xiaonuo.home.modular.structure.relation.entity.HomeRelation;
import vip.xiaonuo.home.modular.structure.relation.enums.HomeRelationCategoryEnum;
import vip.xiaonuo.home.modular.structure.relation.service.HomeRelationService;
import vip.xiaonuo.home.modular.structure.user.entity.HomeUser;
import vip.xiaonuo.home.modular.structure.user.enums.HomeUserStatusEnum;
import vip.xiaonuo.home.modular.structure.user.service.HomeUserService;

import java.util.List;

/**
 * 公司信息Service接口实现类
 *
 * @author Mr.wu
 * @date  2025/02/21 22:06
 **/
@Service
public class HomeCompanyServiceImpl extends ServiceImpl<HomeCompanyMapper, HomeCompany> implements HomeCompanyService {
    private static final String SNOWY_SYS_DEFAULT_PASSWORD_KEY = "SNOWY_SYS_DEFAULT_PASSWORD";

    @Resource
    private HomeUserService homeUserService;

    @Resource
    private HomeOrgService homeOrgService;

    @Resource
    private HomePositionService homePositionService;

    @Resource
    private DevConfigApi devConfigApi;

    @Resource
    private HomeRelationService homeRelationService;

    @Override
    public Page<HomeCompany> page(HomeCompanyPageParam homeCompanyPageParam) {
        QueryWrapper<HomeCompany> queryWrapper = new QueryWrapper<HomeCompany>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(homeCompanyPageParam.getCompanyName())){
            queryWrapper.lambda().like(HomeCompany::getCompanyName, homeCompanyPageParam.getCompanyName());
        }
        if(ObjectUtil.isNotEmpty(homeCompanyPageParam.getCompanyTel())){
            queryWrapper.lambda().eq(HomeCompany::getCompanyTel, homeCompanyPageParam.getCompanyTel());
        }
        if (ObjectUtil.isNotEmpty(homeCompanyPageParam.getStartCompanyLimited()) && ObjectUtil.isNotEmpty(homeCompanyPageParam.getEndCompanyLimited())) {
            queryWrapper.lambda().between(HomeCompany::getCompanyLimited, homeCompanyPageParam.getStartCompanyLimited() + " 00:00:01", homeCompanyPageParam.getEndCompanyLimited() + " 23:59:59");
        }
        if(ObjectUtil.isNotEmpty(homeCompanyPageParam.getCompanyType())){
            queryWrapper.lambda().eq(HomeCompany::getCompanyType, homeCompanyPageParam.getCompanyType());
        }
        if(ObjectUtil.isAllNotEmpty(homeCompanyPageParam.getSortField(), homeCompanyPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(homeCompanyPageParam.getSortOrder());
            queryWrapper.orderBy(true, homeCompanyPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(homeCompanyPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(HomeCompany::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(HomeCompanyAddParam homeCompanyAddParam) {
        HomeCompany homeCompany = BeanUtil.toBean(homeCompanyAddParam, HomeCompany.class);
        this.save(homeCompany);
        //部门信息
        HomeOrg homeOrg = new HomeOrg();
        homeOrg.setParentId("0");
        homeOrg.setName(homeCompany.getCompanyName());
        homeOrg.setCategory("COMPANY");
        homeOrg.setSortCode(1);
        homeOrg.setCompanyId(homeCompany.getId());
        homeOrgService.save(homeOrg);//同时新建部门名
        //岗位信息
        HomePosition homePosition = new HomePosition();
        homePosition.setName("企业管理员");
        homePosition.setCategory("HIGH");
        homePosition.setSortCode(1);
        homePosition.setOrgId(homeOrg.getId());
        homePosition.setCompanyId(homeCompany.getId());
        homePositionService.save(homePosition);
        //企业管理员信息
        HomeUser homeUser = new HomeUser();
        homeUser.setAccount(homeCompany.getCompanyTel());
        homeUser.setName(homeCompany.getCompanyAbbreviation()+"企业管理员");
        homeUser.setAvatar(CommonAvatarUtil.generateImg(homeUser.getName()));
        homeUser.setGender("男");
        homeUser.setPhone(homeCompany.getCompanyTel());
        homeUser.setPositionId(homePosition.getId());
        homeUser.setOrgId(homeOrg.getId());//所属部门信息
        homeUser.setPassword(CommonCryptogramUtil.doHashValue(devConfigApi.getValueByKey(SNOWY_SYS_DEFAULT_PASSWORD_KEY)));
        homeUser.setUserStatus(HomeUserStatusEnum.ENABLE.getValue());
        homeUser.setCompanyId(homeCompany.getId());
        homeUserService.save(homeUser);
        //角色授权
        HomeRelation homeRelation = new HomeRelation();
        homeRelation.setObjectId(homeUser.getId());
        homeRelation.setTargetId(homeCompanyAddParam.getCompanyType().equals("0") ? "1892161328797184001" : homeCompanyAddParam.getCompanyType().equals("1") ? "1893322462780956674" : "1895122944990003202");//此处是根据公司类型不同创建不同的角色
        homeRelation.setCategory(HomeRelationCategoryEnum.SYS_USER_HAS_ROLE.getValue());
        homeRelationService.save(homeRelation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(HomeCompanyEditParam homeCompanyEditParam) {
        HomeCompany homeCompany = this.queryEntity(homeCompanyEditParam.getId());
        BeanUtil.copyProperties(homeCompanyEditParam, homeCompany);
        this.updateById(homeCompany);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<HomeCompanyIdParam> homeCompanyIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(homeCompanyIdParamList, HomeCompanyIdParam::getId));
    }

    @Override
    public HomeCompany detail(HomeCompanyIdParam homeCompanyIdParam) {
        return this.queryEntity(homeCompanyIdParam.getId());
    }

    @Override
    public HomeCompany queryEntity(String id) {
        HomeCompany homeCompany = this.getById(id);
        if(ObjectUtil.isEmpty(homeCompany)) {
            throw new CommonException("公司信息不存在，id值为：{}", id);
        }
        return homeCompany;
    }
}
